package com.qf.hospital.system.realm;

import com.qf.hospital.system.entity.SysUser;
import com.qf.hospital.system.service.SysUserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class CustomRealm extends AuthorizingRealm {

   /* public static void main(String[] args) {
        System.out.println(new Md5Hash("admin", "abcdefghijklmn", 1024).toString());
        // 9e6cdcb0d94b5e670790186f01526abf
    }*/

    @Autowired
    private SysUserService sysUserService;

    {
        HashedCredentialsMatcher md5Matcher = new HashedCredentialsMatcher();
        md5Matcher.setHashAlgorithmName("MD5");
        md5Matcher.setHashIterations(1024);
        this.setCredentialsMatcher(md5Matcher);
    }


    // 认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //1. token中存放着用户输入的用户名和密码 - 获取用户名
        String username = (String) token.getPrincipal();

        //2. 根据用户名去数据库查询用户信息
        SysUser user = sysUserService.findByUsername(username);
        if(user == null){
            // 用户名错误
            return null;   // UnknownAccountException
        }

        //3. 判断密码    principal: 存放用户表示,一般存放数据库查询的用户信息   Credentials: 存放数据库查询出来的正确的密码
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user,user.getPwd(),"");
        info.setCredentialsSalt(ByteSource.Util.bytes(user.getSalt()));
        return info;
    }


    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }
}
